from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import striptags

import markdown, datetime

class Forum(models.Model):
    title = models.CharField(maxlength=200)
    slug = models.SlugField(prepopulate_from=("title",))
    description = models.TextField(blank=True)
    added = models.DateTimeField('date_created', editable=False)
    latest_post = models.ForeignKey('Post', related_name="forum_latest", blank=True, null=True)
    post_count = models.IntegerField(default=0, editable=False)

    def __str__(self):
        return self.title

    class Admin:
        pass

    def save(self):
        if not self.id:
            self.added = datetime.datetime.now()
        self.title = striptags(self.title)
        self.updated = datetime.datetime.now()
        self.description_html = markdown.markdown(striptags(self.description))
        super(Forum, self).save()


class Topic(models.Model):
    forum = models.ForeignKey(Forum)
    title = models.CharField(maxlength=200)
    slug = models.SlugField(prepopulate_from=("title",))
    locked = models.BooleanField(default=False)
    sticky = models.BooleanField(default=False)
    views = models.IntegerField(default=0, editable=False)
    added = models.DateTimeField('date_created', editable=False)
    updated = models.DateTimeField('date_updated', editable=False)
    latest_post = models.ForeignKey('Post', related_name="topic_latest", null=True, blank=True, editable=False)
    post_count = models.IntegerField(default=0, blank=True, editable=False)

    def __str__(self):
        return self.title

    class Admin:
        pass

    def save(self):
        if not self.id:
            self.added = datetime.datetime.now()
        self.title = striptags(self.title)
        self.updated = datetime.datetime.now()
        super(Topic, self).save()

class Post(models.Model):
    topic = models.ForeignKey(Topic)
    user = models.ForeignKey(User)
    description = models.TextField()
    description_html = models.TextField(editable=False)
    updated = models.DateTimeField(editable=False)
    added = models.DateTimeField(editable=False)
    count = models.IntegerField(default=1, editable=False)

    def __str__(self):
        return self.topic.title + ": " + str(self.id)

    class Admin:
        pass

    def save(self):
        if not self.id:
            self.added = datetime.datetime.now()
        self.updated = datetime.datetime.now()
        self.description_html = markdown.markdown(striptags(self.description))
        super(Post, self).save()

class UserProfile(models.Model):
    user = models.OneToOneField(User)
    bio = models.TextField('bio', blank=True)
    website = models.URLField(blank=True)
    image = models.ImageField(upload_to="beastly/user_images/")
    watching = models.ManyToManyField(Topic, related_name="users", blank=True)

    def __str__(self):
        return self.user.username + "_profile"

    class Admin:
        pass
